#include <asm/sbidef.h>
#include <asm/sbiasm.h>

//#here places the size of os image
.equ os_size_loc, 0x502001fc
//#sd read 64 blocks once(if enough)
.equ read_block_size, 64

//#jump to here to start
.equ start_entrypoint, 0x50201000

.data
msg: .string "It's a bootloader!\n\r"

.text
.global main

main:
//#fence on all memory and I/O
	fence
	csrr a0, mhartid
	// a0 is mhartid, a1 is the pointer of fdt
	move s0,a0
	move s1,a1
//#print a \n to avoid system output error...
	li a0, 10
	SBI_CALL SBI_CONSOLE_PUTCHAR
	move a0, s0
	bnez a0, secondary
//#call BIOS print string "It's bootblock!"
	la a0, msg
	SBI_CALL SBI_CONSOLE_PUTSTR

//#get os_size
	lui s1,%hi(os_size_loc)
	addi s1,s1,%lo(os_size_loc)
	lh s1,0(s1)
	li s2,0x8000 //#512 * 64
	lui t1,%hi(0x501F9000)
	addi t1,t1,%lo(0x501F9000)
	li t2,1
//#prepare load size
prepare:
	li a1,64
	bge s1,a1,load_start
	mv a1,s1
load_start:
//#call sbi_sd_read function
	add a0,t1,s2
	mv t1,a0
	//#a1 prepared
	mv a2,t2
	SBI_CALL SBI_SD_READ
	sub s1,s1,a1
	add t2,t2,a1
    bgtz s1,prepare
//#jump to start_entrypoint

	lui a0,%hi(0x50201000)
	addi  a0,a0,%lo(0x50201000)
	jr  a0
secondary:
	lui a0,%hi(0x50201000)
	addi  a0,a0,%lo(0x50201000)
   	csrw stvec,t1
   	addi t1,zero,0x333
   	csrw sie,t1
   	addi t1,zero,0x22
   	csrw sstatus,t1
wait_for_wakeup:
	wfi
	j wait_for_wakeup
// while(1) --> stop here
stop:
	j stop
	nop




